/*
链表
*/
class LinkedList {
  constructor() {
    this.count = 0;
    this.head = undefined;
  }
  push(item) {
    let node = new Node(item)
    let current;
    if(!this.head) {
      this.head = node
    } else {
      current = this.head
      while(current.next) {
        current = current.next
      }
      current.next = node;
    }
    this.count++;
  }
  removeAt(index) {
    if(index >= 0 && index < this.count) {
      let current = this.head;
      // 第一项
      if(index === 0) {
        this.head = current.next;
      } else {
        let previous;
        for(let i = 0; i < index; i++) {
          previous = current;
          current = current.next;
        }
        // 跳过 current，实现删除的目的
        previous.next = current.next
      }
      this.count--;
      return current.value
    }
    return undefined;
  }
  getItemAt(index) {
    if(index >= 0 && index <= this.count) {
      let current = this.head
      for(let i = 0; i < index; i++) {
        current = current.next
      }
      return current
    }
    return undefined;
  }
  insert(item, index) {
    if(index >= 0 && index <= this.count) {
      let node = new Node(item)
      let current = this.head;
      if(index == 0) {
        node.next = current
        this.head = node
      } else {
        let previous = this.getItemAt(index - 1)
        current = previous.next
        node.next = current
        previous.next = node
      }
      this.count++;
      return true;
    }
    return false;
  }
  remove(item) {
    let index = this.indexOf(item);
    return this.removeAt(index)
  }
  isEmpty() {
    return this.count == 0
  }
  size() {
    return this.count;
  }
  toString() {
    if (!this.head) {
      return "";
    }
    let string = this.head.value;
    let current = this.head.next;
    for (let i = 1; i < this.count && current; i++) {
      string += `,${current.value}`;
      current = current.next;
    }
    return string;
  }
}
class Node {
    constructor(value) {
      this.value = value;
      this.next = undefined;
    }
  }
  module.exports = LinkedList